<template>
  <div class="model-config-container">
    <!-- 左侧树形结构 -->
    <div class="tree-section">
      <a-card title="模型树" :bordered="false" size="small">
        <template #extra>
          <a-button type="primary" size="small" @click="handleAdd(null)">
            <PlusOutlined />
            新增根节点
          </a-button>
        </template>
        <a-spin :spinning="treeLoading">
          <a-tree
            v-if="treeData.length > 0"
            :tree-data="treeData"
            :field-names="{ key: 'FMID', title: 'displayName', children: 'children' }"
            :show-line="true"
            :default-expand-all="true"
            @select="handleTreeSelect"
          >
            <template #title="{ dataRef }">
              <div class="tree-node-title">
                <span class="tree-node-text">{{ dataRef.displayName }}</span>
                <a-dropdown :trigger="['click']">
                  <span class="tree-node-more" @click.stop>
                    <MoreOutlined />
                  </span>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item @click="handleAdd(dataRef)">
                        <PlusCircleOutlined />
                        新增子节点
                      </a-menu-item>
                      <a-menu-item @click="handleEdit(dataRef)">
                        <EditOutlined />
                        编辑
                      </a-menu-item>
                      <a-menu-item @click="handleDelete(dataRef)">
                        <DeleteOutlined />
                        删除
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </div>
            </template>
          </a-tree>
          <a-empty v-else description="暂无数据" />
        </a-spin>
      </a-card>
    </div>

    <!-- 右侧编辑区 -->
    <div class="edit-section">
      <a-card title="模型详情" :bordered="false" size="small">
        <template #extra>
          <a-space v-if="currentModel && editMode">
            <a-button @click="handleCancel">取消</a-button>
            <a-button type="primary" @click="handleSave" :loading="saveLoading">
              保存
            </a-button>
          </a-space>
          <a-button v-else-if="currentModel" type="primary" @click="enableEditMode">
            编辑
          </a-button>
        </template>
        <a-spin :spinning="detailLoading">
          <template v-if="currentModel">
            <!-- 基本信息表单 -->
            <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="模型ID">
                    <a-input v-model:value="currentModel.FMID" :disabled="!isNewModel" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="父节点ID">
                    <a-input v-model:value="currentModel.FPID" :disabled="!editMode" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="模型名称" required>
                    <a-input v-model:value="currentModel.FNAME" :disabled="!editMode" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="租户ID" required>
                    <a-input v-model:value="currentModel.FTNID" :disabled="!editMode" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="业务类型">
                    <a-select v-model:value="currentModel.FBIZ_CATEGORY" :disabled="!editMode">
                      <a-select-option value="PLAT">PLAT</a-select-option>
                      <a-select-option value="SYS">SYS</a-select-option>
                      <a-select-option value="EREMARK">EREMARK</a-select-option>
                      <a-select-option value="PLATLog">PLATLog</a-select-option>
                      <a-select-option value="SYSLog">SYSLog</a-select-option>
                      <a-select-option value="EREMARKLog">EREMARKLog</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="表名">
                    <a-input v-model:value="currentModel.FTABLE_NAME" :disabled="!editMode" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="编码">
                    <a-input v-model:value="currentModel.FCODE" :disabled="!editMode" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="状态">
                    <a-select v-model:value="currentModel.FSTATE" :disabled="!editMode">
                      <a-select-option :value="1">启用</a-select-option>
                      <a-select-option :value="0">禁用</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="24">
                  <a-form-item label="备注" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
                    <a-textarea 
                      v-model:value="currentModel.FMEMO" 
                      :disabled="!editMode" 
                      :rows="2"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>

            <!-- SQL 脚本 Tab 页 -->
            <a-divider />
            <a-tabs v-model:activeKey="activeTab">
              <a-tab-pane key="query" tab="查询语句">
                <div class="editor-container">
                  <div ref="queryEditorRef" class="sql-editor"></div>
                </div>
              </a-tab-pane>
              <a-tab-pane key="execute" tab="执行语句">
                <div class="editor-container">
                  <div ref="executeEditorRef" class="sql-editor"></div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </template>
          <a-empty v-else description="请选择模型节点" />
        </a-spin>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue';
import { message, Modal } from 'ant-design-vue';
import * as monaco from 'monaco-editor';
import { 
  PlusOutlined, 
  PlusCircleOutlined, 
  EditOutlined, 
  DeleteOutlined,
  MoreOutlined
} from '@ant-design/icons-vue';
import { 
  getModelTree, 
  getModelDetail, 
  createModel, 
  updateModel, 
  deleteModel,
  ModelTreeNode, 
  ModelDetail 
} from '@/api/model';
import { v4 as uuidv4 } from '@/utils/guid';
import dayjs from 'dayjs';

// 状态定义
const treeLoading = ref(false);
const detailLoading = ref(false);
const saveLoading = ref(false);
const treeData = ref<ModelTreeNode[]>([]);
const currentModel = ref<ModelDetail | null>(null);
const activeTab = ref('query');
const editMode = ref(false);
const isNewModel = ref(false);
const originalModel = ref<ModelDetail | null>(null);

// Monaco Editor 实例
const queryEditorRef = ref<HTMLElement | null>(null);
const executeEditorRef = ref<HTMLElement | null>(null);
let queryEditor: monaco.editor.IStandaloneCodeEditor | null = null;
let executeEditor: monaco.editor.IStandaloneCodeEditor | null = null;

/**
 * 构建树形数据
 */
function buildTreeData(nodes: ModelTreeNode[]): ModelTreeNode[] {
  const map = new Map<string, ModelTreeNode>();
  const roots: ModelTreeNode[] = [];

  // 第一遍：创建所有节点的映射，并添加 displayName
  nodes.forEach((node) => {
    const nodeWithDisplay = {
      ...node,
      displayName: `[${node.FTNID}]${node.FNAME}`,
      children: [],
    };
    map.set(node.FMID, nodeWithDisplay);
  });

  // 第二遍：构建树形结构
  nodes.forEach((node) => {
    const currentNode = map.get(node.FMID);
    if (!currentNode) return;

    if (!node.FPID || node.FPID === '') {
      // 根节点
      roots.push(currentNode);
    } else {
      // 子节点
      const parent = map.get(node.FPID);
      if (parent) {
        if (!parent.children) {
          parent.children = [];
        }
        parent.children.push(currentNode);
      } else {
        // 如果找不到父节点，也作为根节点
        roots.push(currentNode);
      }
    }
  });

  return roots;
}

/**
 * 加载模型树数据
 */
async function loadTreeData() {
  try {
    treeLoading.value = true;
    const response = await getModelTree('*');
    
    if (response && response.length > 0 && response[0].rows) {
      const nodes = response[0].rows;
      treeData.value = buildTreeData(nodes);
    } else {
      treeData.value = [];
      message.warning('暂无模型数据');
    }
  } catch (error) {
    console.error('加载模型树失败:', error);
    message.error('加载模型树失败');
    treeData.value = [];
  } finally {
    treeLoading.value = false;
  }
}

/**
 * 加载模型详情
 */
async function loadModelDetail(fmid: string) {
  try {
    detailLoading.value = true;
    const response = await getModelDetail(fmid);
    
    if (response && response.length > 0 && response[0].rows && response[0].rows.length > 0) {
      currentModel.value = response[0].rows[0];
      
      // 等待 DOM 更新后初始化编辑器
      await nextTick();
      initEditors();
    } else {
      message.warning('模型详情为空');
      currentModel.value = null;
    }
  } catch (error) {
    console.error('加载模型详情失败:', error);
    message.error('加载模型详情失败');
    currentModel.value = null;
  } finally {
    detailLoading.value = false;
  }
}

/**
 * 树节点选择事件
 */
function handleTreeSelect(selectedKeys: string[]) {
  if (selectedKeys.length > 0) {
    const fmid = selectedKeys[0];
    loadModelDetail(fmid);
  }
}

/**
 * 启用编辑模式
 */
function enableEditMode() {
  editMode.value = true;
  isNewModel.value = false;
  originalModel.value = JSON.parse(JSON.stringify(currentModel.value));
  updateEditorReadOnly(false);
}

/**
 * 新增模型
 */
function handleAdd(parentNode: ModelTreeNode | null) {
  const newModel: ModelDetail = {
    FMID: uuidv4(),
    FPID: parentNode?.FMID || '',
    FFID: 0,
    FTNID: parentNode?.FTNID || '*',
    FCODE: '',
    FNAME: '',
    FSHORT_NAME: '',
    FSTATE: 1,
    FTYPE: '',
    FADD_USER: localStorage.getItem('username') || 'admin',
    FADD_TIME: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    FLAST_USER: '',
    FLAST_TIME: null,
    FMEMO: '',
    FLASTMODIFIED: '',
    FEXPLAIN: '',
    FBIZ_CATEGORY: '',
    FTABLE_NAME: '',
    FCMD_QUERY: '',
    FCMD_EXECUTE: '',
  };

  currentModel.value = newModel;
  editMode.value = true;
  isNewModel.value = true;
  originalModel.value = null;
  
  nextTick(() => {
    initEditors();
    updateEditorReadOnly(false);
  });
}

/**
 * 编辑模型
 */
function handleEdit(node: ModelTreeNode) {
  loadModelDetail(node.FMID);
  setTimeout(() => {
    enableEditMode();
  }, 100);
}

/**
 * 删除模型
 */
function handleDelete(node: ModelTreeNode) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除模型「${node.FNAME}」吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        await deleteModel(node.FMID, node.FTNID);
        message.success('删除成功');
        
        // 刷新树
        await loadTreeData();
        
        // 清空详情
        if (currentModel.value?.FMID === node.FMID) {
          currentModel.value = null;
          editMode.value = false;
        }
      } catch (error) {
        console.error('删除失败:', error);
      }
    },
  });
}

/**
 * 保存模型
 */
async function handleSave() {
  if (!currentModel.value) return;

  // 验证必填字段
  if (!currentModel.value.FNAME) {
    message.error('请输入模型名称');
    return;
  }
  if (!currentModel.value.FTNID) {
    message.error('请输入租户ID');
    return;
  }

  try {
    saveLoading.value = true;

    // 获取编辑器内容
    if (queryEditor) {
      currentModel.value.FCMD_QUERY = queryEditor.getValue();
    }
    if (executeEditor) {
      currentModel.value.FCMD_EXECUTE = executeEditor.getValue();
    }

    // 更新修改信息
    currentModel.value.FLAST_USER = localStorage.getItem('username') || 'admin';
    currentModel.value.FLAST_TIME = dayjs().format('YYYY-MM-DD HH:mm:ss');

    if (isNewModel.value) {
      // 新增
      await createModel(currentModel.value);
      message.success('新增成功');
    } else {
      // 修改
      await updateModel(currentModel.value);
      message.success('保存成功');
    }

    // 退出编辑模式
    editMode.value = false;
    isNewModel.value = false;
    updateEditorReadOnly(true);

    // 刷新树
    await loadTreeData();

    // 刷新当前模型详情
    if (currentModel.value.FMID) {
      await loadModelDetail(currentModel.value.FMID);
    }
  } catch (error) {
    console.error('保存失败:', error);
  } finally {
    saveLoading.value = false;
  }
}

/**
 * 取消编辑
 */
function handleCancel() {
  if (isNewModel.value) {
    // 新增取消，清空详情
    currentModel.value = null;
  } else if (originalModel.value) {
    // 修改取消，恢复原数据
    currentModel.value = JSON.parse(JSON.stringify(originalModel.value));
    nextTick(() => {
      initEditors();
    });
  }
  
  editMode.value = false;
  isNewModel.value = false;
  updateEditorReadOnly(true);
}

/**
 * 初始化 Monaco Editor
 */
function initEditors() {
  if (!currentModel.value) return;

  // 销毁旧的编辑器实例
  if (queryEditor) {
    queryEditor.dispose();
    queryEditor = null;
  }
  if (executeEditor) {
    executeEditor.dispose();
    executeEditor = null;
  }

  // 创建查询语句编辑器
  if (queryEditorRef.value) {
    queryEditor = monaco.editor.create(queryEditorRef.value, {
      value: currentModel.value.FCMD_QUERY || '',
      language: 'sql',
      theme: 'vs-dark',
      automaticLayout: true,
      readOnly: !editMode.value,
      minimap: { enabled: false },
      scrollBeyondLastLine: false,
      fontSize: 13,
      lineNumbers: 'on',
      wordWrap: 'on',
    });
  }

  // 创建执行语句编辑器
  if (executeEditorRef.value) {
    executeEditor = monaco.editor.create(executeEditorRef.value, {
      value: currentModel.value.FCMD_EXECUTE || '',
      language: 'sql',
      theme: 'vs-dark',
      automaticLayout: true,
      readOnly: !editMode.value,
      minimap: { enabled: false },
      scrollBeyondLastLine: false,
      fontSize: 13,
      lineNumbers: 'on',
      wordWrap: 'on',
    });
  }
}

/**
 * 更新编辑器只读状态
 */
function updateEditorReadOnly(readOnly: boolean) {
  if (queryEditor) {
    queryEditor.updateOptions({ readOnly });
  }
  if (executeEditor) {
    executeEditor.updateOptions({ readOnly });
  }
}

/**
 * 监听 activeTab 变化，确保编辑器正确渲染
 */
watch(activeTab, async () => {
  await nextTick();
  if (activeTab.value === 'query' && queryEditor) {
    queryEditor.layout();
  } else if (activeTab.value === 'execute' && executeEditor) {
    executeEditor.layout();
  }
});

/**
 * 组件挂载时加载数据
 */
onMounted(() => {
  loadTreeData();
});

/**
 * 组件卸载时销毁编辑器
 */
onUnmounted(() => {
  if (queryEditor) {
    queryEditor.dispose();
  }
  if (executeEditor) {
    executeEditor.dispose();
  }
});
</script>

<script lang="ts">
import { defineComponent, onUnmounted } from 'vue';

export default defineComponent({
  name: 'ModelConfig',
});
</script>

<style scoped lang="less">
.model-config-container {
  display: flex;
  height: 100%;
  gap: 6px;

  .tree-section {
    width: 220px;
    flex-shrink: 0;

    :deep(.ant-card) {
      height: 100%;
      display: flex;
      flex-direction: column;
      
      .ant-card-head {
        min-height: 36px;
        padding: 0 8px;
        border-bottom: 1px solid #f0f0f0;
        
        .ant-card-head-title {
          padding: 6px 0;
          font-size: 13px;
          font-weight: 500;
        }
        
        .ant-card-extra {
          padding: 6px 0;
        }
      }
      
      .ant-card-body {
        flex: 1;
        padding: 6px;
        overflow-y: auto;
      }
    }
    
    .add-root-btn {
      padding: 0;
      height: 24px;
      width: 24px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      
      .anticon {
        font-size: 14px;
      }
    }

    :deep(.ant-tree) {
      .ant-tree-node-content-wrapper {
        width: 100% !important;
        flex: 1 !important;
        min-width: 0;
      }
      
      .ant-tree-title {
        width: 100%;
        display: flex;
      }
      
      .ant-tree-treenode {
        width: 100%;
      }
    }

    .tree-node-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      flex: 1;
      
      .tree-node-text {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .tree-node-more {
        opacity: 0;
        cursor: pointer;
        font-size: 16px;
        color: #666;
        padding: 0 4px;
        border-radius: 2px;
        transition: all 0.3s;
        flex-shrink: 0;
        
        &:hover {
          color: #1890ff;
          background: #f0f0f0;
        }
      }
      
      &:hover .tree-node-more {
        opacity: 1;
      }
    }
  }

  .edit-section {
    flex: 1;
    overflow: hidden;

    :deep(.ant-card) {
      height: 100%;
      display: flex;
      flex-direction: column;
      
      .ant-card-head {
        min-height: 36px;
        padding: 0 8px;
        border-bottom: 1px solid #f0f0f0;
        
        .ant-card-head-title {
          padding: 6px 0;
          font-size: 13px;
          font-weight: 500;
        }
        
        .ant-card-extra {
          padding: 6px 0;
        }
      }
      
      .ant-card-body {
        flex: 1;
        padding: 6px 8px;
        overflow-y: auto;
      }
    }
    
    :deep(.ant-form) {
      .ant-form-item {
        margin-bottom: 6px;
      }
      
      .ant-form-item-label {
        padding-bottom: 2px;
        
        label {
          font-size: 13px;
          height: 24px;
        }
      }
      
      .ant-input,
      .ant-select-selector,
      .ant-input-number {
        font-size: 13px;
      }
      
      .ant-row {
        margin-bottom: 0;
      }
    }
    
    :deep(.ant-divider) {
      margin: 6px 0;
    }
    
    :deep(.ant-tabs) {
      .ant-tabs-nav {
        margin-bottom: 6px;
      }
      
      .ant-tabs-tab {
        padding: 4px 10px;
        font-size: 13px;
      }
    }
  }

  .editor-container {
    height: calc(100vh - 48px - 32px - 16px - 72px - 36px - 200px);
    min-height: 280px;
    border: 1px solid #303030;
    border-radius: 2px;
    overflow: hidden;

    .sql-editor {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
